﻿using System;
using System.Collections.Generic;
using System.Text;
using AMS.DataAccess.Properties;

namespace AMS.DataAccess
{
    /// <summary>
    /// 一个构造SQL语句的辅助类
    /// </summary>
    internal static class SqlEnumUtils
    {
        /// <summary>
        /// 数值比较运算符
        /// </summary>
        private static readonly string[] NumberOps = new string[] { " = ", " <> ", " > ", " >= ", " < ", " <= ", " IS NULL", " IS NOT NULL" };

        /// <summary>
        /// 字符串比较运算符
        /// </summary>
        private static readonly string[] StringOps = new string[] { " = ", " <> ", " LIKE ", " LIKE ", " LIKE ", " IS NULL", " IS NOT NULL" };

        /// <summary>
        /// 将枚举类型的数值运算值转换成数值比较运算符
        /// </summary>
        /// <param name="op">要转换的值</param>
        /// <returns>转换以的内容</returns>
        public static string NumberOperationsToString(SqlOperations op)
        {
            return NumberOps[(int)op];
        }

        /// <summary>
        /// 将枚举类型的字符串运算值转换成字符串比较运算符
        /// </summary>
        /// <param name="op">要转换的值</param>
        /// <returns>转换以的内容</returns>
        public static string StringOperationsToString(StringOperations op)
        {
            return StringOps[(int)op];
        }

        /// <summary>
        /// 根据 Like 操作符和比较值构造Like表达式
        /// </summary>
        /// <param name="likeOp">操作符</param>
        /// <param name="value">比较值</param>
        /// <returns>结果表达式</returns>
        public static string FormatLike(StringOperations likeOp, string value)
        {
            if (likeOp != StringOperations.Like && likeOp != StringOperations.LeftLike && likeOp != StringOperations.RightLike)
            {
                throw new ArgumentException(Resources.NotLikeOperation);
            }

            switch (likeOp)
            {
                case StringOperations.Like:
                    return string.Format(" LIKE '%{0}%'", value.Replace("'", "''"));

                case StringOperations.LeftLike:
                    return string.Format(" LIKE '%{0}'", value.Replace("'", "''"));

                case StringOperations.RightLike:
                    return string.Format(" LIKE '{0}%'", value.Replace("'", "''"));

                default:
                    // NEVER OCCURED
                    return string.Empty;
            }
        }
    }

}
